package com.adnaan.backend.common.config;

import com.adnaan.backend.common.exception.BizException;
import com.adnaan.backend.common.utils.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * author: adnaan
 * create: 2023-12-06 13:53
 * Description:
 */
@Component
public class FileUpload {

    @Value("${car.profile}")
    private String UPLOAD_FOLDER;


    public String upload(MultipartFile file, String filetype) {
        if (file.isEmpty()) {
            throw new BizException(500, "文件上传为空");
        }
        //获取文件名称
        String originalFilename = file.getOriginalFilename();
        //新文件名称
        String fileName = UUID.randomUUID() + "_" + originalFilename;
        File dest = new File(UPLOAD_FOLDER + "/" + filetype + "/" + fileName);
        if (!dest.getParentFile().exists()) {
            //创建目录
            boolean mkdirs = dest.mkdirs();
            if (!mkdirs) {
                throw new BizException(500, "文件上传失败");
            }
        }
        try {
            //执行拷贝过程
            file.transferTo(dest);
            return Constant.RESOURCE_PREFIX + "/" + filetype + "/" + fileName;
        } catch (IOException e) {
            throw new BizException(500, "文件上传失败");
        }
    }
}
